package cz.muni.fi.pa165.hauntedhouses.service;

import cz.muni.fi.pa165.hauntedhouses.dao.HouseDAO;
import cz.muni.fi.pa165.hauntedhouses.dto.HouseDTO;
import cz.muni.fi.pa165.hauntedhouses.entity.House;
import static cz.muni.fi.pa165.hauntedhouses.util.DTOAndDAOMapper.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * A service layer for house management. 
 * Transactions are controlled here.
 * Allows the use of CRUD methods plus FindBy.
 * @author Jaromir Benda (374289)
 */
@Service
@Transactional
public class HouseServiceImpl implements HouseService {

    @Autowired
    private HouseDAO houseDAO;

    public void setHouseDAO(HouseDAO hDAO) {
        houseDAO = hDAO;
    }

    @Override
    public void create(HouseDTO house) {
        House hs = DTOHouseToEntityHouse(house);
        houseDAO.create(hs);
        house.setId(hs.getId());
        for(int i = 0; i < house.getGhosts().size(); i++){
            house.getGhosts().get(i).setId(hs.getGhosts().get(i).getId());
            for(int j = 0; j < house.getGhosts().get(i).getAbilities().size(); j++){
                house.getGhosts().get(i).getAbilities().get(j)
                        .setId(hs.getGhosts().get(i).getAbilities().get(j).getId());
            }
        }
        for(int i = 0; i < house.getHumans().size(); i++){
            house.getHumans().get(i).setId(hs.getHumans().get(i).getId());
        }
    }

    @Override
    public void update(HouseDTO house) {
        House hs = DTOHouseToEntityHouse(house);
        houseDAO.update(hs);
        house = HouseEntityToDTOHouse(hs);
    }

    @Override
    public void remove(HouseDTO house) {
        houseDAO.remove(DTOHouseToEntityHouse(house));
    }

    @Override
    public HouseDTO get(Long id) {
        return (HouseEntityToDTOHouse(houseDAO.get(id)));
    }

    @Override
    public List<HouseDTO> findAll() {
        List <HouseDTO> dtoList = new ArrayList<>();
        for (House house : houseDAO.findAll()) {
            dtoList.add(HouseEntityToDTOHouse(house));
        }
        return Collections.unmodifiableList(dtoList);
    }

    @Override
    public List<HouseDTO> findByName(String name) {
     List <HouseDTO> dtoList = new ArrayList<>();
        for (House house : houseDAO.findByName(name)) {
            dtoList.add(HouseEntityToDTOHouse(house));
        }
        return Collections.unmodifiableList(dtoList);
    }
           
}